import { createOrder, sendGift } from "@/api/gift";
import { reactive, ref, watch } from "vue";
import { defineStore } from "pinia";
import utils from "@/utils/utils";
export const useCheckoutStore = defineStore("checkout", () => {
  const checkout = ref({});
  const checkoutParams = ref({
    balance: false,
    addressId: null,
    shipList: [],
    isSafe: false,
  });
  const getCheckout = async () => {
    try {
      const res = await sendGift(checkoutParams.value);
      const appUserGoodList = res.data.appUserGoodList
        .map((item) => {
          return {
            ...item,
            num: res.data.appUserGoodList.filter(
              (i) => i.goodId === item.goodId
            ).length,
          };
        })
        .filter((item, index, self) => {
          return self.findIndex((i) => i.goodId === item.goodId) === index;
        });
      checkout.value = res.data;
      checkout.value.appUserGoodList = appUserGoodList;
      checkout.value.total = appUserGoodList.reduce((pre, cur) => {
        return (pre += cur.num);
      }, 0);
    } catch (error) {}
  };
  const createGiftOrder = async () => {
    try {
      const res = await createOrder();
      if (!checkoutParams.value.balance) {
        await utils.Wxpay(res.data.wxPayAppOrderResult);
      }
      utils.showToast("下单成功");
      setTimeout(() => {
        utils.useRouter("/goods_packages/myOrder/myOrder");
      }, 500);
    } catch (error) {
      utils.showToast("下单取消");
    }
  };
  const deleteGoods = (item) => {
    checkout.value.appUserGoodList = checkout.value.appUserGoodList.filter(
      (e) => e.id !== item.id
    );
  };
  // watch(checkoutParams, () => {
  //   getCheckout();
  // });
  return {
    checkout,
    checkoutParams,
    getCheckout,
    createGiftOrder,
    deleteGoods,
  };
});
